# -*- coding: utf-8 -*-
from futu import *
import time
import pandas as pd
import tushare as ts
from datetime import date

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

pb = SimpleFilter()
pb.filter_min = 0.1
pb.filter_max = 5
pb.stock_field = StockField.PB_RATE
pb.is_no_filter = False

roe = FinancialFilter() 
roe.filter_min = 10
roe.filter_max = 60
roe.stock_field = StockField.RETURN_ON_EQUITY_RATE
roe.is_no_filter = False
roe.sort = SortDir.DESCEND
roe.quarter = FinancialQuarter.ANNUAL

turnover = AccumulateFilter()
turnover.filter_min = 500000000
turnover.filter_max = 100000000000
turnover.stock_field = StockField.TURNOVER
turnover.days = 3
turnover.is_no_filter = False

turnoverrate = AccumulateFilter()
turnoverrate.filter_min = 2
turnoverrate.filter_max = 80
turnoverrate.stock_field = StockField.TURNOVER_RATE
turnoverrate.days = 5
turnoverrate.is_no_filter = False

ema_long = PatternFilter()
ema_long.stock_field = StockField.EMA_ALIGNMENT_LONG
ema_long.ktype = KLType.K_60M
ema_long.is_no_filter = False

nBegin = 0
last_page = False
ret_list = list()
futu_codes = []
while not last_page:
    nBegin += len(ret_list)
    ret, ls1 = quote_ctx.get_stock_filter(
                                        market=Market.HK, 
                                        # market=Market.SH, 
                                        filter_list=[turnover,turnoverrate,ema_long,
                                        ], begin=nBegin)  
    if ret == RET_OK:
        last_page, all_count, ret_list = ls1
        for item in ret_list:
            futu_codes.append(item.stock_code)
    else:
        print('error: ', ls1)
    time.sleep(3)

# while last_page:
#     nBegin += len(ret_list)
#     ret, ls2 = quote_ctx.get_stock_filter(
#                                         market=Market.HK, 
#                                         # market=Market.SH, 
#                                         filter_list=[roe], 
#                                         begin=nBegin)  
#     if ret == RET_OK:
#         last_page, all_count, ret_list = ls2
#         for item in ret_list:
#             if item.pb_rate>4:
#                 print(item.roic)
#                 # futu_codes.append(item.stock_code)
#         # print(futu_codes)
#     else:
#         print('error: ', ls2)
#     time.sleep(3)

pro = ts.pro_api("349ea0b339d16e8e92dec8a3daeb5ee46c14e3067fc53b133d6fab38")
trade_cal = pro.query("trade_cal", start_date="20240930", end_date=date.today().strftime("%Y%m%d"))
trade_cal = trade_cal[(trade_cal["is_open"] == 1)]["cal_date"].tolist()
df = pd.DataFrame()
for date in trade_cal:
    df0 = pro.ths_hot(market='港股',
        trade_date=date,
        fields='ts_code,trade_date,ts_name,rank')
    time.sleep(0.12)
    df = pd.concat([df,df0], ignore_index=True).head(50)
df['ts_code'] = "HK."+df["ts_code"].str.slice(stop=-3)
df.dropna(axis=1)
# print(df)
df = df[df['ts_code'].isin(futu_codes)]
df['ts_code'] = pd.Categorical(df['ts_code'], categories=futu_codes, ordered=True)
df.sort_values('ts_code', inplace=True)
print(df)
ret, data = quote_ctx.get_market_snapshot(futu_codes)
quote_ctx.close()
picked_codes = df.head(4).ts_code.tolist()
print(picked_codes)
